<script setup>
import 'leaflet/dist/leaflet.css'
import '@supermap/iclient-leaflet/css/index'

import iServerConfigUrl from '/iServerConfig.json?url'

import { ElMessage } from 'element-plus'
import $ from 'jquery'
import axios from 'axios'

import L from 'leaflet'
import '@supermap/iclient-leaflet'
import 'proj4leaflet'

import { inject } from 'vue'

const optionsProps = {
    value: 'value',
    label: 'label'
}
</script>

<template>
    <div class="imageSearch">
        <span class="collectionsTitle">影像集合</span>
        <el-select-v2 class="collectionsSelect" v-model="collection" filterable :options="options" :props="optionsProps" placeholder="请选择需要查询的影像集合"
            @change="handleSelectedCollectionChanged"></el-select-v2>
        <span class="collectionsListTitle">影像列表</span>
        <el-table class="imageSearchedResult" :data="imageCollectionsData" @selection-change="handleSelectionChanged">
            <el-table-column type="selection" align="center" width="36" fixed></el-table-column>
            <el-table-column property="id" label="ID" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column property="filename" label="文件名称" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column property="datetime" label="添加时间" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="缩略图" align="center" show-overflow-tooltip>
                <template #default="scope">
                    <span>
                        <el-image :src="scope.row.img" />
                    </span>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
export default {
    name: 'ImageService',
    data() {
        return {
            imageServiceUrl: undefined,
            collection: '',
            options: [],
            imageCollectionsData: [],
            imageLayers: [],
            map: undefined
        }
    },
    mounted() {
        var map = inject('map');

        axios.get(iServerConfigUrl).then(res => {
            var iServerConfig = res.data;
            this.imageServiceUrl = `${iServerConfig.urls.ImageService.protocol}://${iServerConfig.urls.ImageService.hostname}:${iServerConfig.urls.ImageService.port}/${iServerConfig.urls.ImageService.imageServiceUrl}`;
            
            this.map = map;

            $("#map")[0].style.width = 'calc(100vw - 800px)';
            map._size.x = document.body.clientWidth - 800;

            map.options.crs = L.CRS.EPSG4326;
            map.options.maxZoom = 20;
            map.options.minZoom = 0;
            map.flyTo([31.12, 104.48], 4);

            // 加载影像服务集合信息
            this.loadImageServiceCollections(map);
        }).catch(err => {
            ElMessage.error(err.stack);
        });
    },
    methods: {
        // 加载影像服务集合信息
        loadImageServiceCollections(map) {
            axios.get(`${this.imageServiceUrl}/collections.json`).then(res => {
                var data = res.data;
                for (let i = 0; i < data.length; i++) {
                    var collection = data[i];
                    var keywords = collection.keywords;
                    for (let j = 0; j < keywords.length; j++) {
                        var keyword = keywords[j];
                        this.options[this.options.length] = {
                            value: keyword,
                            label: keyword,
                            collection: collection
                        };
                    }
                }
            }).catch(err => {
                console.log(err);
            });
        },

        // 清空当前地图的图层
        clearMapLayers(map) {
            this.imageCollectionsData = [];
            map.eachLayer(layer => {
                layer.remove();
            });
        },

        // 选择的影像集合发生改变时
        handleSelectedCollectionChanged(keyword) {
            var map = this.map;
            this.clearMapLayers(map);

            var collection = this.options.find((option) => {
                return keyword === option.value;
            }).collection;
            var bbox = collection.extent.spatial.bbox[0];
            map.fitBounds([[bbox[1], bbox[2]], [bbox[3], bbox[0]]]);

            var itemsUrl = collection.links[3].href;
            axios.get(itemsUrl).then(res => {
                var items = res.data.content;
                if (items.length > 0) {
                    for (let i = 0; i < items.length; i++) {
                        var item = items[i];
                        this.imageCollectionsData[this.imageCollectionsData.length] = {
                            id: `${item.collection}.${item.id}`,
                            filename: item.assets.data.title,
                            datetime: item.properties.addtime,
                            img: item.assets.thumbnail.href
                        };

                        new L.polygon(item.geometry.coordinates[0].map(p => { return [p[1], p[0]] }), { color: '#B7FEB755' }).addTo(map);
                    }
                }
            }).catch(err => {
                console.log(err);
            });
        },

        // 选择影像数据添加到地图显示
        handleSelectionChanged(rows) {
            var map = this.map;
            if (this.imageLayers.length > 0) {
                for (let i = 0; i < this.imageLayers.length; i++) {
                    var imageLayer = this.imageLayers[i];
                    imageLayer.remove();
                }
                this.imageLayers = [];
            }

            var imageLayernames = this.imageLayers.map((imageLayer) => {
                return imageLayer.name;
            });
            for (let i = 0; i < rows.length; i++) {
                var row = rows[i];
                imageLayernames[imageLayernames.length] = row.filename;
            }
            if (imageLayernames.length > 0) {
                var imageLayer = new L.supermap.ImageTileLayer(this.imageServiceUrl, {
                    collectionId: this.collection,
                    names: imageLayernames
                });
                this.imageLayers[this.imageLayers.length] = imageLayer;
                map.addLayer(imageLayer);
            }
        }
    }
}
</script>

<style scoped>
.imageSearch {
    z-index: 999;
    height: calc(100vh - 81px);
    width: 800px;
    position: absolute;
    right: 0px;
    background-color: azure;
}

.collectionsTitle {
    top: 46px;
    position: inherit;
    right: 20px;
    width: calc(100% - 44px);
    line-height: 26px;
    font-weight: 600;
    font-size: large;
    text-align: left;
}

.collectionsSelect {
    z-index: 1001;
    top: 80px;
    position: inherit;
    right: 20px;
    width: calc(100% - 40px);
}

.collectionsListTitle {
    top: 166px;
    position: inherit;
    right: 20px;
    width: calc(100% - 44px);
    line-height: 26px;
    font-weight: 600;
    font-size: large;
    text-align: left;
}

.imageSearchedResult {
    overflow: auto;
    z-index: 1000;
    top: 200px;
    position: inherit;
    right: 20px;
    width: calc(100% - 40px);
    line-height: 32px;
    max-height: 620px;
    height: 620px;
    font-size: 15px;
}
</style>